package todo_plan

import (
	"encoding/json"
	"github.com/gin-gonic/gin"
	"io/ioutil"
	"log"
	"tao-admin/internal/model"
)

type PlanService struct {
	PlanManager *PlanManager
}

func NewPlanService() *PlanService {
	return &PlanService{
		PlanManager: &PlanManager{},
	}
}

func (service *PlanService) GetPlanInfos(ctx *gin.Context) ([]model.ToDoPlanTab, int64, error) {
	condition := &SearchPlanCondition{}
	if title, isExist := ctx.GetQuery("title"); isExist == true {
		condition.Title = &title
	}
	if description, isExist := ctx.GetQuery("description"); isExist == true {
		condition.Description = &description
	}
	if type1, isExist := ctx.GetQuery("type"); isExist == true {
		condition.Type = &type1
	}
	if status, isExist := ctx.GetQuery("status"); isExist == true {
		condition.Status = &status
	}

	list, total, err := service.PlanManager.SearchPlanByConditionMng(ctx, condition)
	if err != nil {
		return nil, 0, err
	}
	log.Printf("SearchByConditionMng, list: %v, total: %v", &list, total)
	return list, total, nil
}

func (service *PlanService) CreatePlanItem(ctx *gin.Context) (err error, msg string) {
	var item model.ToDoPlanTab
	bodyBytes, err := ioutil.ReadAll(ctx.Request.Body)
	if err != nil {
		return err, "数据解析出错！(Read Request.Body)"
	}
	err = json.Unmarshal(bodyBytes, &item)
	if err != nil {
		return err, "数据解析出错！(Unmarshal)"
	}

	if item.Title == nil || item.Type == nil || item.Status == nil ||
		item.Description == nil {
		return nil, "存在必填项未填写！"
	}
	err = service.PlanManager.CreatePlanMng(ctx, item)
	if err != nil {
		return err, "插入数据出错！"
	}
	return nil, ""
}

func (service *PlanService) UpdatePlanItem(ctx *gin.Context) (err error, msg string) {
	var item model.ToDoPlanTab
	bodyBytes, err := ioutil.ReadAll(ctx.Request.Body)
	if err != nil {
		return err, "数据解析出错！(Read Request.Body)"
	}
	err = json.Unmarshal(bodyBytes, &item)
	if err != nil {
		return err, "数据解析出错！(Unmarshal)"
	}
	if item.Id == nil {
		return nil, "Id必传！"
	}
	err = service.PlanManager.UpdatePlanMng(ctx, item)
	if err != nil {
		return err, "更新数据出错！"
	}
	return nil, ""
}

func (service *PlanService) DeletePlanItem(ctx *gin.Context) (err error, msg string) {
	var item model.ToDoPlanTab
	bodyBytes, err := ioutil.ReadAll(ctx.Request.Body)
	if err != nil {
		return err, "数据解析出错！(Read Request.Body)"
	}
	err = json.Unmarshal(bodyBytes, &item)
	if err != nil {
		return err, "数据解析出错！"
	}
	if item.Id == nil {
		return nil, "Id必传！"
	}
	err = service.PlanManager.DeletePlanMng(ctx, item)
	if err != nil {
		return err, "删除数据出错！"
	}
	return nil, ""
}
